package com.moses.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author Moses
 * @email shenhuohui@gmail.com
 * @date 2021/5/31 22:43
 */
public class Client {
    public static void main(String[] args) throws FileNotFoundException {
        // 从输入流中获取 channel，channel 主要用来打开读写定位等，相当于File
        try (FileChannel fileChannel = new FileInputStream("").getChannel()){
            // Buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            while (true){
                int count = fileChannel.read(byteBuffer);
                if(count == -1) break;
                // The limit is set to the current position and then the position is set to zero
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()){
                    byte b = byteBuffer.get();
                    System.out.println((char) b);
                }
                // Clears this buffer.  The position is set to zero, the limit is set to the capacity, and the mark is discarded
                byteBuffer.clear();
                // 整理未读的数据到数组前面
                // byteBuffer.compact();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
